import {defineStore} from 'pinia';
import myAxios from "@/axios/axios.js";

export const useLikeStore = defineStore('like', {
    state: () => ({
        likeMap: new Map(), // 存储帖子ID和点赞状态的映射
        likeCountMap: new Map() // 存储帖子ID和点赞数量的映射
    }),
    actions: {
        /**
         * 点赞
         * @param {number} postId 帖子ID
         * @returns {Promise<boolean>} 操作结果
         */
        async like(postId) {
            try {
                const res = await myAxios.post(`/like/${postId}`);
                if (res.code === 0) {
                    this.likeMap.set(postId, true);
                    this.likeCountMap.set(postId, (this.likeCountMap.get(postId) || 0) + 1);
                    return true;
                }
                return false;
            } catch (error) {
                console.error('点赞失败', error);
                return false;
            }
        },

        /**
         * 取消点赞
         * @param {number} postId 帖子ID
         * @returns {Promise<boolean>} 操作结果
         */
        async unLike(postId) {
            try {
                const res = await myAxios.delete(`/like/${postId}`);
                if (res.code === 0) {
                    this.likeMap.set(postId, false);
                    this.likeCountMap.set(postId, Math.max(0, (this.likeCountMap.get(postId) || 0) - 1));
                    return true;
                }
                return false;
            } catch (error) {
                console.error('取消点赞失败', error);
                return false;
            }
        },

        /**
         * 获取点赞数量
         * @param {number} postId 帖子ID
         * @returns {Promise<number>} 点赞数量
         */
        async getLikeCount(postId) {
            if (this.likeCountMap.has(postId)) {
                return this.likeCountMap.get(postId);
            }
            try {
                const res = await myAxios.get(`/like/count/${postId}`);
                if (res.code === 0) {
                    this.likeCountMap.set(postId, res.data);
                    return res.data;
                }
                return 0;
            } catch (error) {
                console.error('获取点赞数量失败', error);
                return 0;
            }
        },

        /**
         * 检查是否已点赞
         * @param {number} postId 帖子ID
         * @returns {Promise<boolean>} 是否已点赞
         */
        async checkHasLiked(postId) {
            if (this.likeMap.has(postId)) {
                return this.likeMap.get(postId);
            }
            try {
                const res = await myAxios.get(`/like/hasLiked/${postId}`);
                if (res.code === 0) {
                    this.likeMap.set(postId, res.data);
                    return res.data;
                }
                return false;
            } catch (error) {
                console.error('检查是否已点赞失败', error);
                return false;
            }
        }
    }
});